// src/components/Workbench.js
import { Row, Col, Card, Table, Button, List, Tag, Progress, Input, Avatar, Statistic, Dropdown, Menu, Drawer, Modal, Badge, Typography, Space, Empty, message, Spin } from '@/utils/antd-imports';
import { SearchOutlined, BellOutlined, MoreOutlined, UserOutlined, ArrowUpOutlined, ArrowDownOutlined, EyeOutlined, EditOutlined, FileTextOutlined, BarChartOutlined, PieChartOutlined, LineChartOutlined, PlusOutlined, SettingOutlined, DeleteOutlined, LogoutOutlined, DashboardOutlined, TeamOutlined, ProjectOutlined, MoneyCollectOutlined, ApartmentOutlined, FileOutlined, FileAddOutlined, FileDoneOutlined, SwapOutlined, DollarOutlined, FileSyncOutlined, FileProtectOutlined, AuditOutlined, BookOutlined, CheckCircleOutlined, CarOutlined, SafetyCertificateOutlined, SolutionOutlined, ExclamationCircleOutlined, WarningOutlined, InfoCircleOutlined, CloseCircleOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import wsManager from '../utils/websocket';
import { useAuth } from '../context/AuthContext';
import { acceptanceMemberApi, projectAcceptanceApi } from '../api/projectAcceptanceApi';
















import { Line, Pie, Bar } from '@ant-design/charts';
import workbenchData from '../data/workbenchData.json';

const { Search } = Input;

const { Text } = Typography;

const Workbench = ({ onProjectSelect, getMenuItems }) => {
  const { user } = useAuth();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [manageMode, setManageMode] = useState(false);
  const [quickActions, setQuickActions] = useState(workbenchData.quickActions);
  const [selectedAction, setSelectedAction] = useState(null);
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [acceptanceData, setAcceptanceData] = useState([]);
  const [loadingAcceptance, setLoadingAcceptance] = useState(false);

  // 加载验收单数据
  const loadAcceptanceData = async () => {
    if (!user?.employeeId) {
      console.warn('用户员工ID不存在，无法加载验收单数据');
      return;
    }

    setLoadingAcceptance(true);
    try {
      // 先获取验收成员数据
      const memberResponse = await acceptanceMemberApi.getMembersByEmployee(user.employeeId);
      console.log('✅ 验收成员响应:', memberResponse);
      
      if (memberResponse.code === 200) {
        const members = memberResponse.data || [];
        console.log('✅ 验收成员列表:', members);
        
        // 获取所有验收单ID
        const acceptanceIds = [...new Set(members.map(member => member.acceptanceId))];
        console.log('📋 提取的验收单ID列表:', acceptanceIds);
        
        // 并行获取所有验收单详情
        const acceptancePromises = acceptanceIds.map(id => 
          projectAcceptanceApi.getAcceptanceById(id)
        );
        
        const acceptanceResponses = await Promise.all(acceptancePromises);
        console.log('📋 验收单详情响应结果:', acceptanceResponses);
        
        // 合并验收单详情和成员信息，只显示未验收的验收单
        const enrichedData = acceptanceResponses
          .filter(response => {
            const isValid = response.code === 200;
            console.log(`🔍 验收单ID ${response.data?.id || '未知'} 响应状态: ${response.code}`, {
              code: response.code,
              message: response.message,
              data: response.data
            });
            return isValid;
          })
          .map(response => {
            const acceptance = response.data;
            const relatedMembers = members.filter(member => member.acceptanceId === acceptance.id);
            console.log(`📊 验收单ID ${acceptance.id} 关联成员数:`, relatedMembers.length);
            
            return {
              ...acceptance,
              // 添加成员相关信息
              memberCount: relatedMembers.length,
              totalEstimatedHours: relatedMembers.reduce((sum, member) => sum + (member.estimatedHours || 0), 0),
              totalActualHours: relatedMembers.reduce((sum, member) => sum + (member.actualHours || 0), 0),
              totalAmount: relatedMembers.reduce((sum, member) => sum + (member.settlementAmount || 0), 0)
            };
          })
          .filter(acceptance => {
            // 显示待验收、验收中、已验收的验收单
            const shouldShow = acceptance.status === '待验收' || 
                              acceptance.status === '验收中' || 
                              acceptance.status === '已验收';
            console.log(`🎯 验收单ID ${acceptance.id} 状态 "${acceptance.status}" 是否显示:`, shouldShow);
            return shouldShow;
          });
        
        console.log('🎉 最终渲染到表格的数据:', enrichedData);
        console.log('📈 数据数量:', enrichedData.length);
        setAcceptanceData(enrichedData);
      } else {
        message.error('加载验收单数据失败：' + memberResponse.message);
      }
    } catch (error) {
      console.error('加载验收单数据失败：', error);
      message.error('加载验收单数据失败，请检查网络连接');
    } finally {
      setLoadingAcceptance(false);
    }
  };

  // 初始化通知数据和验收单数据
  useEffect(() => {
    // 从本地存储加载通知历史
    const savedNotifications = localStorage.getItem('notifications');
    if (savedNotifications) {
      try {
        const parsed = JSON.parse(savedNotifications);
        setNotifications(parsed.slice(0, 5)); // 工作台只显示最近5条
        setUnreadCount(parsed.filter(n => !n.read).length);
      } catch (error) {
        console.error('加载通知历史失败:', error);
      }
    }

    // 加载验收单数据
    loadAcceptanceData();

    // 监听WebSocket消息
    const handleNotification = (payload) => {
      addNotification('notification', payload);
    };

    const handleAlert = (payload) => {
      addNotification('alert', payload);
    };

    const handleUrgent = (payload) => {
      addNotification('urgent', payload);
    };

    const handleApproval = (payload) => {
      addNotification('approval', payload);
    };

    const handleProject = (payload) => {
      addNotification('project', payload);
    };

    const handleSystem = (payload) => {
      addNotification('system', payload);
    };

    // 添加监听器
    wsManager.addListener('notification', handleNotification);
    wsManager.addListener('alert', handleAlert);
    wsManager.addListener('urgent', handleUrgent);
    wsManager.addListener('approval', handleApproval);
    wsManager.addListener('project', handleProject);
    wsManager.addListener('system', handleSystem);

    return () => {
      wsManager.removeListener('notification', handleNotification);
      wsManager.removeListener('alert', handleAlert);
      wsManager.removeListener('urgent', handleUrgent);
      wsManager.removeListener('approval', handleApproval);
      wsManager.removeListener('project', handleProject);
      wsManager.removeListener('system', handleSystem);
    };
  }, []);

  // 添加新通知
  const addNotification = (type, payload) => {
    const newNotification = {
      id: Date.now() + Math.random(),
      type,
      title: payload.title || payload.message || '新通知',
      description: payload.description || '',
      timestamp: new Date(),
      read: false,
      data: payload.data || {},
      actions: payload.actions || []
    };

    setNotifications(prev => {
      const updated = [newNotification, ...prev].slice(0, 5); // 只保留最近5条
      return updated;
    });

    setUnreadCount(prev => prev + 1);
  };

  // 标记通知为已读
  const markAsRead = (id) => {
    setNotifications(prev => {
      const updated = prev.map(n => 
        n.id === id ? { ...n, read: true } : n
      );
      return updated;
    });
    setUnreadCount(prev => Math.max(0, prev - 1));
  };

  // 获取通知图标
  const getNotificationIcon = (type) => {
    switch (type) {
      case 'alert':
        return <ExclamationCircleOutlined style={{ color: '#faad14' }} />;
      case 'urgent':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      case 'approval':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'project':
        return <InfoCircleOutlined style={{ color: '#1890ff' }} />;
      case 'system':
        return <WarningOutlined style={{ color: '#722ed1' }} />;
      default:
        return <BellOutlined style={{ color: '#8c8c8c' }} />;
    }
  };

  // 获取通知类型标签
  const getNotificationTag = (type) => {
    const tagMap = {
      'notification': { color: 'blue', text: '通知' },
      'alert': { color: 'orange', text: '预警' },
      'urgent': { color: 'red', text: '紧急' },
      'approval': { color: 'green', text: '审批' },
      'project': { color: 'cyan', text: '项目' },
      'system': { color: 'purple', text: '系统' }
    };
    
    const tag = tagMap[type] || { color: 'default', text: '其他' };
    return <Tag color={tag.color} size="small">{tag.text}</Tag>;
  };

  // 格式化时间
  const formatTime = (timestamp) => {
    const now = new Date();
    const diff = now - timestamp;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return timestamp.toLocaleDateString();
  };

  // 图表配置
  const lineConfig = {
    data: workbenchData.lineChartData,
    padding: 'auto',
    xField: 'month',
    yField: 'value',
    smooth: true,
    lineStyle: {
      stroke: '#1890ff',
      lineWidth: 2,
    },
    point: {
      size: 4,
      style: {
        fill: '#1890ff',
        stroke: '#fff',
        lineWidth: 2,
      },
    },
    areaStyle: {
      fill: 'l(270) 0:#ffffff 0.5:#f0f8ff 1:#1890ff',
    },
  };

  const pieConfig = {
    data: workbenchData.pieChartData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'element-active' }],
    color: ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'],
  };

  const progressConfig = {
    data: workbenchData.progressData,
    xField: 'progress',
    yField: 'project',
    seriesField: 'project',
    legend: false,
    color: ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'],
  };

  // 处理验收单点击事件
  const handleAcceptanceClick = (acceptanceRecord) => {
    console.log('点击验收单:', acceptanceRecord);
    if (onProjectSelect) {
      onProjectSelect({
        type: 'settlement-detail',
        projectId: acceptanceRecord.projectId,
        projectCode: acceptanceRecord.projectCode,
        projectName: acceptanceRecord.projectName
      });
    }
  };

  // 计算验收截止状态
  const calculateAcceptanceStatus = (acceptanceTime) => {
    if (!acceptanceTime) return { status: 'unknown', text: '未知', color: 'default' };
    
    const now = new Date();
    const acceptanceDate = new Date(acceptanceTime);
    const diffTime = acceptanceDate.getTime() - now.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays < 0) {
      return { status: 'overdue', text: '已逾期', color: 'red' };
    } else if (diffDays <= 3) {
      return { status: 'urgent', text: '即将逾期', color: 'orange' };
    } else if (diffDays <= 7) {
      return { status: 'warning', text: `${diffDays}天后截止`, color: 'blue' };
    } else {
      return { status: 'normal', text: `${diffDays}天后截止`, color: 'green' };
    }
  };

  // 项目表格列
  const projectColumns = [
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      key: 'projectCode',
      render: (text) => (
        <span style={{ fontWeight: 'bold', color: '#1890ff' }}>
          {text || '-'}
        </span>
      ),
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
    },
    {
      title: '子项目名称',
      dataIndex: 'subProjectName',
      key: 'subProjectName',
    },
    {
      title: '预计工时',
      dataIndex: 'totalEstimatedHours',
      key: 'totalEstimatedHours',
      render: (text) => text ? `${text}小时` : '-',
    },
    {
      title: '验收金额',
      dataIndex: 'acceptanceAmount',
      key: 'acceptanceAmount',
      render: (amount) => (
        <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
          ¥{amount?.toLocaleString() || '-'}
        </span>
      ),
    },
    {
      title: '验收截止时间',
      dataIndex: 'acceptanceDate',
      key: 'acceptanceDate',
      render: (date) => {
        if (!date) return '-';
        return new Date(date).toLocaleDateString();
      },
    },
    {
      title: '验收状态',
      dataIndex: 'acceptanceDate',
      key: 'acceptanceStatus',
      render: (acceptanceDate) => {
        const statusInfo = calculateAcceptanceStatus(acceptanceDate);
        return (
          <Tag color={statusInfo.color}>
            {statusInfo.text}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Button 
          type="link" 
          size="small" 
          icon={<EyeOutlined />}
          onClick={() => handleAcceptanceClick(record)}
          style={{ padding: 0 }}
        >
          查看详情
        </Button>
      ),
    },
  ];

  const moreMenu = (
    <Menu>
      <Menu.Item key="1">导出数据</Menu.Item>
      <Menu.Item key="2" onClick={loadAcceptanceData}>刷新</Menu.Item>
      <Menu.Item key="3">设置</Menu.Item>
    </Menu>
  );

  // 图标映射
  const iconComponents = {
    FileTextOutlined: <FileTextOutlined />,
    BarChartOutlined: <BarChartOutlined />,
    PieChartOutlined: <PieChartOutlined />,
    LineChartOutlined: <LineChartOutlined />,
    EditOutlined: <EditOutlined />,
    DashboardOutlined: <DashboardOutlined />,
    TeamOutlined: <TeamOutlined />,
    ProjectOutlined: <ProjectOutlined />,
    MoneyCollectOutlined: <MoneyCollectOutlined />,
    ApartmentOutlined: <ApartmentOutlined />,
    SettingOutlined: <SettingOutlined />,
    LogoutOutlined: <LogoutOutlined />,
    FileOutlined: <FileOutlined />,
    FileAddOutlined: <FileAddOutlined />,
    FileDoneOutlined: <FileDoneOutlined />,
    SwapOutlined: <SwapOutlined />,
    DollarOutlined: <DollarOutlined />,
    FileSyncOutlined: <FileSyncOutlined />,
    FileProtectOutlined: <FileProtectOutlined />,
    AuditOutlined: <AuditOutlined />,
    BookOutlined: <BookOutlined />,
    CheckCircleOutlined: <CheckCircleOutlined />,
    CarOutlined: <CarOutlined />,
    SafetyCertificateOutlined: <SafetyCertificateOutlined />,
    SolutionOutlined: <SolutionOutlined />
  };

  // 从菜单项生成可用功能选项
  const generateMenuActions = (items) => {
    const actions = [];
    items.forEach(item => {
      if (item.children) {
        // 处理有子菜单的项目
        item.children.forEach(child => {
          actions.push({
            key: child.key,
            label: child.label,
            icon: child.icon,
            color: getRandomColor(),
            parentKey: item.key
          });
        });
      } else if (item.component) {
        // 处理直接有组件的菜单项
        actions.push({
          key: item.key,
          label: item.label,
          icon: item.icon,
          color: getRandomColor()
        });
      }
    });
    return actions;
  };

  // 生成随机颜色
  const getRandomColor = () => {
    const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16'];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  // 所有可用功能选项（基于菜单项）
  const menuItems = getMenuItems ? getMenuItems() : [];
  const allActions = menuItems.length > 0 ? generateMenuActions(menuItems) : [
    { label: '新建文档', icon: 'FileTextOutlined', color: '#1890ff' },
    { label: '数据分析', icon: 'BarChartOutlined', color: '#52c41a' },
    { label: '图表统计', icon: 'PieChartOutlined', color: '#faad14' },
    { label: '趋势分析', icon: 'LineChartOutlined', color: '#f5222d' },
    { label: '编辑内容', icon: 'EditOutlined', color: '#722ed1' },
  ];

  // 添加功能
  const handleAddAction = (action) => {
    if (!quickActions.some(item => item.label === action.label)) {
      setQuickActions([...quickActions, action]);
    }
    setDrawerVisible(false);
  };

  // 处理常用功能点击
  const handleQuickActionClick = (action) => {
    if (onProjectSelect) {
      onProjectSelect({
        type: 'menu-navigation',
        key: action.key,
        parentKey: action.parentKey,
        label: action.label
      });
    }
  };

  // 删除功能
  const handleDeleteAction = (index) => {
    const newActions = [...quickActions];
    newActions.splice(index, 1);
    setQuickActions(newActions);
  };

  return (
    <div style={{ padding: '24px', background: '#f5f7fa', minHeight: '100vh' }}>

      {/* 主要内容区域 */}
      <Row gutter={24}>
        {/* 左侧列 - 项目状态和看板 */}
        <Col span={16}>
        <Row gutter={24} style={{ marginBottom: 24 }}>
          {workbenchData.statisticsData.map((stat, index) => (
            <Col span={6} key={index}>
              <Card>
                <Statistic
                  title={stat.title}
                  value={stat.value}
                  valueStyle={{ color: stat.color }}
                  prefix={stat.value >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                />
              </Card>
            </Col>
          ))}
        </Row>
          <Card 
            title="我的项目" 
            extra={
              <Dropdown overlay={moreMenu} placement="bottomRight">
                <MoreOutlined style={{ cursor: 'pointer' }} />
              </Dropdown>
            }
            style={{ marginBottom: 24 }}
          >
            <Spin spinning={loadingAcceptance}>
              <Table 
                columns={projectColumns} 
                dataSource={acceptanceData} 
                pagination={false}
                size="small"
                rowKey="id"
                locale={{
                  emptyText: '暂无项目数据'
                }}
              />
            </Spin>
          </Card>

          {/* 看板 - 折线图 */}
          <Card title="项目数据趋势" style={{ marginBottom: 24 }}>
            <Line {...lineConfig} height={200} />
          </Card>

          {/* 项目进度 */}
          <Card 
            title="项目进度" 
            extra={<Button type="link">查看更多</Button>}
          >
            <Bar {...progressConfig} height={200} />
            <List
              size="small"
              dataSource={workbenchData.projectProgressData}
              renderItem={(item, index) => (
                <List.Item>
                  <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                    <span>{item}</span>
                    <Progress 
                      percent={workbenchData.progressData[index]?.progress || 0} 
                      size="small" 
                      style={{ width: 200 }}
                    />
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 右侧列 */}
        <Col span={8}>
          {/* 常用功能 */}
          <Card 
            title={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>常用功能</span>
                <div>
                  <Button 
                    type="text" 
                    icon={manageMode ? <LogoutOutlined /> : <SettingOutlined />} 
                    onClick={() => setManageMode(!manageMode)}
                    style={{ marginRight: 8 }}
                  >
                    {manageMode ? '退出' : '管理'}
                  </Button>
                  <Button 
                    type="text" 
                    icon={<PlusOutlined />} 
                    onClick={() => setDrawerVisible(true)}
                  />
                </div>
              </div>
            }
            style={{ marginBottom: 24 }}
          >
            <Row gutter={[16, 16]}>
              {quickActions.map((action, index) => (
                <Col span={12} key={index}>
                  <div style={{ position: 'relative' }}>
                    <Button 
                      type="text" 
                      style={{ 
                        width: '100%', 
                        height: 80,
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        border: '1px solid #f0f0f0'
                      }}
                      onClick={() => handleQuickActionClick(action)}
                    >
                      <div style={{ fontSize: 24, color: action.color, marginBottom: 8 }}>
                        {action.icon && typeof action.icon === 'string' ? iconComponents[action.icon] : action.icon || <FileTextOutlined />}
                      </div>
                      <span>{action.label}</span>
                    </Button>
                    {manageMode && (
                      <Button 
                        type="text" 
                        danger
                        icon={<DeleteOutlined />} 
                        style={{ 
                          position: 'absolute', 
                          top: 0, 
                          right: 0,
                          zIndex: 1
                        }}
                        onClick={() => handleDeleteAction(index)}
                      />
                    )}
                  </div>
                </Col>
              ))}
            </Row>
          </Card>

          {/* 人员成本占比饼图 */}
          <Card 
            title="2003435-上汽通用人员成本占比图" 
            extra={<Button type="link">查看更多</Button>}
            style={{ marginBottom: 24 }}
          >
            <Pie {...pieConfig} height={200} />
          </Card>

          {/* 消息通知 */}
          <Card 
            title={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Space>
                  <BellOutlined />
                  <span>消息通知</span>
                  {unreadCount > 0 && (
                    <Badge count={unreadCount} size="small" />
                  )}
                </Space>
              </div>
            }
          >
            {notifications.length === 0 ? (
              <Empty
                description="暂无通知"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                style={{ padding: '20px 0' }}
              />
            ) : (
              <List
                size="small"
                dataSource={notifications}
                renderItem={item => (
                  <List.Item
                    style={{
                      padding: '8px 0',
                      cursor: item.read ? 'default' : 'pointer',
                      backgroundColor: item.read ? 'transparent' : '#f6ffed',
                      borderRadius: '4px',
                      marginBottom: '4px'
                    }}
                    onClick={() => !item.read && markAsRead(item.id)}
                  >
                    <List.Item.Meta
                      avatar={getNotificationIcon(item.type)}
                      title={
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Text strong={!item.read} style={{ fontSize: '13px' }}>
                            {item.title}
                          </Text>
                          <Space size="small">
                            {getNotificationTag(item.type)}
                            <Text type="secondary" style={{ fontSize: '11px' }}>
                              {formatTime(item.timestamp)}
                            </Text>
                          </Space>
                        </div>
                      }
                      description={
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          {item.description}
                        </Text>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </Card>
        </Col>
      </Row>

      {/* 添加功能抽屉 */}
      <Drawer
        title="添加常用功能"
        placement="top"
        height="auto"
        visible={drawerVisible}
        onClose={() => setDrawerVisible(false)}
      >
        <Row gutter={[16, 16]}>
          {allActions.map((action, index) => (
            <Col span={6} key={index}>
              <Button 
                type="text" 
                style={{ 
                  width: '100%', 
                  height: 80,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  border: '1px solid #f0f0f0'
                }}
                onClick={() => handleAddAction(action)}
                disabled={quickActions.some(item => item.label === action.label)}
              >
                <div style={{ fontSize: 24, color: action.color, marginBottom: 8 }}>
                  {action.icon && typeof action.icon === 'string' ? iconComponents[action.icon] : action.icon || <FileTextOutlined />}
                </div>
                <span>{action.label}</span>
              </Button>
            </Col>
          ))}
        </Row>
      </Drawer>
    </div>
  );
};

export default Workbench;